package ue.galaxy;

import java.util.Random;

import org.jdom.Element;

import ue.resources.Deposit;
import ue.resources.Resource;

public class Asteroid {
	protected Deposit deposit;
	
	protected int duration;
	protected double value;
	protected int mainResource;
	
	public Asteroid(int seed, double value) {
		if(value < 0 || value > 1) {
			System.err.println("ERROR: Asteroid Value out of bounds. Must be between 0 and 1.");
			System.exit(1);
		}
		
		this.value = value;
		
		Random random = new Random(seed);
		
		mainResource = random.nextInt(Deposit.LENGTH - 2);
		
		int[] max = new int[Deposit.LENGTH];
		for(int i = 0; i < Deposit.LENGTH; i++) {
			if(i == mainResource) {
				max[i] = (int)(50 + value * 50 + random.nextInt((int)(value * 50)) - value * 25);
			} else {
				max[i] = random.nextInt((int)(1 + 9 * value));
			}
		}
		
		deposit = new Deposit(random.nextInt(), max);
		
		duration = random.nextInt(100);
		if(duration == 0) duration -= 1;
	}
	
	public Asteroid(Element element) {
		if(element.getName() != "asteroid") {
			System.err.println("ERROR: Incorrect XML Asteroid Element: Wrong element name");
			System.exit(1);
		}
		
		duration = Integer.parseInt(element.getChildText("duration"));
		value = Double.parseDouble(element.getChildText("value"));
		mainResource = Integer.parseInt(element.getChildText("mainresource"));
		
		deposit = new Deposit(element.getChild("deposit"));
	}
	
	public Asteroid(Deposit deposit, int duration) {
		this.deposit = deposit;
		this.duration = duration;
	}
	
	@Override
	public String toString() {
		return Resource.values()[mainResource].name() + ": " + duration + "; " + value + "; " + deposit.toString();
	}
	
	public Element toXMLElement() {
		Element element = new Element("asteroid");
		
		Element duration = new Element("duration");
		duration.setText("" + this.duration);
		
		Element value = new Element("value");
		value.setText("" + this.value);
		
		Element mainResource = new Element("mainresource");
		mainResource.setText("" + this.mainResource);
		
		element.addContent(duration);
		element.addContent(value);
		element.addContent(mainResource);
		element.addContent(deposit.toXMLElement());
		
		return element;
	}

	public Deposit getDeposit() {
		return deposit;
	}

	public void setDeposit(Deposit deposit) {
		this.deposit = deposit;
	}

	public int getDuration() {
		return duration;
	}

	public void setDuration(int duration) {
		this.duration = duration;
	}

	public double getValue() {
		return value;
	}

	public void setValue(double value) {
		this.value = value;
	}

	public int getMainResource() {
		return mainResource;
	}

	public void setMainResource(int mainResource) {
		this.mainResource = mainResource;
	}
}
